package com.zim.aliot.controller;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.utils.StringUtils;
import com.google.common.util.concurrent.RateLimiter;
import com.zim.aliot.constant.RedisConstant;
import com.zim.aliot.dataobject.CarsDo;
import com.zim.aliot.dataobject.RltCarDeviceMachine;
import com.zim.aliot.enums.ResultEnum;
import com.zim.aliot.exception.IotApiException;
import com.zim.aliot.listener.StartCommandLineRunner;
import com.zim.aliot.service.CarsService;
import com.zim.aliot.util.ResultVOUtils;
import com.zim.aliot.vo.ResultVO;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class IndexController {
	private final RateLimiter rateLimiter = RateLimiter.create(0.1);
	
    @Autowired
    private StartCommandLineRunner startCommandLineRunner; 
    
    @Autowired
    private DefaultAcsClient defaultAcsClient;
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    @Autowired
    private CarsService carsService;
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    
    
    @RequestMapping(value = { "/", "/checkHeartbeat" })
    public ResultVO<String> Index() {
        ResultVO<String> resultVO = new ResultVO<>();
        resultVO.setCode(0);
        resultVO.setMsg("心跳正常");
    	log.error("时间:{}",new Date());
    	if (rateLimiter.tryAcquire()) {
			
			log.info("[GPS保存的数据]");
		}
        return resultVO;
    }
    
    @RequestMapping("checkIotClinet")
    public ResultVO<Object> IotAcsClient(@RequestParam(name = "token",defaultValue="",required=true) String token) {
    	String tokenString = "f30173557ee54d6e9c60857ee30889a2";
    	if(StringUtils.isEmpty(token) || !tokenString.equals(token)) {
    		throw new IotApiException(ResultEnum.PARAM_ERROR);
    	}
        System.out.println(defaultAcsClient);
        return ResultVOUtils.success();
    }
    
    @RequestMapping("mns/stop")
    public ResultVO<Object> mnsStop() {
        startCommandLineRunner.stop();
    
        return ResultVOUtils.success();
    }
    
    @RequestMapping("checkRedis")
    public ResultVO<Object> RedisConnection(@RequestParam(name = "token",defaultValue="",required=true) String token){
    	String tokenString = "f30173557ee54d6e9c60857ee30889a2";
    	if(StringUtils.isEmpty(token) || !tokenString.equals(token)) {
    		throw new IotApiException(ResultEnum.PARAM_ERROR);
    	}
    	try {
    		stringRedisTemplate.opsForValue().getAndSet(token, tokenString);
        	stringRedisTemplate.expire(tokenString, RedisConstant.EXPIRE,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("[redis连接失败]:{}",e.getMessage());
			return ResultVOUtils.error(ResultEnum.ERROR.getCode(), "redis连接失败");
		}
    	
    	return ResultVOUtils.success();
    }
    
    @RequestMapping("checkMongo")
    public ResultVO<Object> mongoConnection(@RequestParam(name = "token",defaultValue="",required=true) String token){
    	String tokenString = "f30173557ee54d6e9c60857ee30889a2";
    	if(StringUtils.isEmpty(token) || !tokenString.equals(token)) {
    		throw new IotApiException(ResultEnum.PARAM_ERROR);
    	}
    	
    	try {
    		CarsDo CarsDo = mongoTemplate.findOne(new Query(), CarsDo.class);
    		return ResultVOUtils.success(CarsDo);
		} catch (Exception e) {
			log.error("[mongo连接失败]:{}",e.getMessage());
			return ResultVOUtils.error(ResultEnum.ERROR.getCode(),"查询失败");
		}
    	
    	
    }
    
    @RequestMapping(value = "/tongbuMg", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public void tongbuMg() {
	    List<RltCarDeviceMachine> oldCars = mongoTemplate.findAll(RltCarDeviceMachine.class);
	    
	    oldCars.forEach(item->{
	        if(!item.getCarUniqueId().isEmpty() && !item.getDeviceName().isEmpty()) {
	            CarsDo carsDo = new CarsDo();
	            carsDo.setVin(item.getCarUniqueId());
	            carsDo.setDeviceName(item.getDeviceName());
	            carsDo.setSupplierNo(1376920002);
	            
	            carsService.save(carsDo);
	        }
	        
	    });
        
    }

}
